package kt.com.bilin.coin.helper.loadsir

import android.view.View
import android.widget.RelativeLayout
import com.bilin.coin.R
import kt.com.bilin.coin.common.dp
import com.kingja.loadsir.callback.Callback
import com.kingja.loadsir.callback.SuccessCallback
import com.kingja.loadsir.core.LoadService
import com.kingja.loadsir.core.LoadSir
import kt.com.bilin.coin.utils.Logger
import java.lang.Exception

/**
 * Created by zhoucl on 2018/11/26 0026.
 */
object LoadSirHelper {
    fun registerNotDefault(target: Any, callback: Callback? = null, listener: (() -> Unit)? = null): LoadService<*> {
        val builder = LoadSir.beginBuilder()
        callback?.let { builder.addCallback(it) }
        return builder.build().register(target) { listener?.invoke() }
    }

    fun registerMultipleNotDefault(target: Any, callback: MutableList<Callback>? = null, listener: (() -> Unit)? = null): LoadService<*> {
        val builder = LoadSir.beginBuilder()
        callback?.forEach { builder.addCallback(it) }
        return builder.build().register(target) { listener?.invoke() }
    }

    fun register(target: Any, callback: ArrayList<Callback>? = null, listener: (() -> Unit)? = null): LoadService<*> {
        val builder = LoadSir.beginBuilder()
        callback?.forEach { builder.addCallback(it) }
        builder.addCallback(LoadingCallback()).addCallback(ErrorCallback()).addCallback(
                EmptyCallback()
        ).addCallback(
                NotNetworkCallback()
        ).setDefaultCallback(SuccessCallback::class.java)
        return builder.build().register(target) { listener?.invoke() }
    }

    fun changePosition(mLoadService: LoadService<*>?, top: Int) {
        try {
            mLoadService?.run {
                setCallBack(EmptyCallback::class.java) { _, view -> doChangePosition(view.findViewById(R.id.ll_text), top) }
                setCallBack(LoadingCallback::class.java) { _, view -> doChangePosition(view.findViewById(R.id.ll_loading), top) }
                setCallBack(ErrorCallback::class.java) { _, view -> doChangePosition(view.findViewById(R.id.ll_text), top) }
            }
        } catch (e: Exception) {
            Logger.e(e)
        }
    }

    private fun doChangePosition(view: View, top: Int) {
        (view.layoutParams as RelativeLayout.LayoutParams).apply {
            removeRule(RelativeLayout.CENTER_IN_PARENT)
            addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE)
            topMargin = top.dp
        }
    }
}